package com.pl.util;

import java.util.Properties;
import java.util.Set;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

public class SelfPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{
	
	private static Logger log = LogManager.getLogger();
	
	public void setGollfPropFiles(Set<String> gollfPropFiles) {  
  
        Properties properties = new Properties();  
        for (String gollfPropFile : gollfPropFiles) {  
  
           try {  

                Properties prop = new Properties();
                prop.load(SelfPropertyPlaceholderConfigurer.class.getClassLoader().getResourceAsStream(gollfPropFile)); 
                
                if(!prop.isEmpty()) {  
                	
                	Set<Object> keys = prop.keySet();
                	for (Object key : keys) {
                		
                		String keyStr = (String) key;
                		String value = "";
                		
                		//默认先使用系统变量，再使用环境变量，再使用配置文件
                		String pro = System.getProperty(keyStr);
                		if(pro != null) {
                			value = pro;
                			prop.put(keyStr, value);
                			log.debug("{} sysPro {}={}", gollfPropFile, keyStr, value);
                			continue;
                		}
                		
                		String evn = System.getenv(keyStr);
                		if(evn != null) {
                			value = evn;
                			prop.put(keyStr, value);
                			log.debug("{} sysEnv {}={}", gollfPropFile, keyStr, value);
                			continue;
                		}
                		
                		value = prop.getProperty(keyStr);
                		log.debug("{} {}={}", gollfPropFile, keyStr, value);
					}
                	
                    properties.putAll(prop);  
                }  
                
            } catch (Exception e) {  
            	e.printStackTrace();
            } 
        }  
  
        this.setProperties(properties); 
        //关键方法,调用的PropertyPlaceholderConfigurer中的方法,  
        //通过这个方法将自定义加载的properties文件加入spring中  
    }  
}
